class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception
  before_action :set_global_var
  before_action :set_model
  before_action :redirect_if_not_login
  before_action :set_obj, only: %i(show edit update destroy)

  helper_method :user_signed_in?, :is_dev?, :is_pro?

  def index

  end

  def new
    @obj = @model.new
  end

  def create
    flag = true
    e_notice = nil
    begin
      # @obj = @model.create(permitted_params)
      @obj = @model.create!(permitted_params)
    rescue Exception => e
      @obj = @model.new(permitted_params)
      e_notice = e.message
      flag = false
    end
    err_msg = @obj.try(:errors).try(:messages).try(:values).try(:join, ',')

    flag = false if err_msg.present?

    if flag
      redirect_to :back, notice: '创建成功！'
    else
      flash[:notice] = e_notice
      render 'new'
    end

  end

  def edit
  end

  def update
    if @obj.update(permitted_params)
      redirect_to :back, notice: '操作成功！'
    else
      flash[:notice] = '操作失败，请联系客服人员！！！'
      render 'edit'
    end
  end

  def show
  end

  def destroy
    flag = true
    begin
      @obj.destroy
    rescue
      flag = false
    end
    flash[:notice] = flag ? '删除成功！' : '删除失败，请联客服人员！！！'
    redirect_back fallback_location: { action: "index" }
  end

  def set_model
    begin
      @model = Object.const_get(self.class.name.gsub(/sController/,''))
    rescue
      @model = nil
    end
  end

  def set_obj
    @obj = @model&.find_by(id: params[:id])
  end

  def user_signed_in?
    session[:current_user_id].present? && @current_user.present?
  end

  def set_global_var
    if session[:current_user_id].present?
      c_user = User.find_by(id: session[:current_user_id])
      if c_user.present?
        if @current_user.nil?
          @current_user = c_user
          @current_user_id = c_user.id
        end
      else
      end
      $request = request
    else
      @current_user = nil
      @current_user_id = nil
    end
  end

  def redirect_if_not_login
    if @current_user.present? && (session[:last_at].blank? or session[:last_at] > 12.hour.ago)
      session[:last_at] = Time.now
    else
      session['return_to_back'] = request.fullpath
      redirect_to login_path
    end
  end

  def is_dev?
    Rails.env.development?
  end

  def is_pro?
    Rails.env.production?
  end

  protected
  def permitted_params
    params.require(@model.model_name.singular.to_sym).permit(@model.column_names.map(&:to_sym) - %w(updated_at created_at))
  end
end
